<template>
  <div class="contribute">
    <el-form
      ref="contributeForm"
      :model="contributeForm"
      :rules="rules"
      label-width="100px"
      class="contribute__form"
      size="medium"
      :hide-required-asterisk="false"
    >
      <el-form-item label="标题" placeholder="请输入标题" prop="title">
        <el-input
          v-model="contributeForm.title"
          minlength="10"
          maxlength="75"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="class">
        <el-cascader
          v-model="contributeForm.class"
          placeholder="请选择分类"
          :options="classOptions"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="标题图片" prop="titleImg">
        <el-upload
          :action="`${appUrl}/api/news/img`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :before-upload="handleBeforeUpload"
          :on-exceed="handleOnExceed"
          :limit="1"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item
        label="内容"
        prop="content"
        class="contribue__form__content"
      >
        <client-only>
          <mavon-editor
            ref="md"
            v-model="content"
            :toolbars="toolbars"
            @imgAdd="$imgAdd"
            @imgDel="$imgDel"
            @change="change"
          />
        </client-only>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('contributeForm')">{{
          id === '' ? '立即提交' : '修改完成'
        }}</el-button>
        <el-button @click="resetForm('contributeForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import _ from 'lodash'
import { APP__URL, IMAGES } from '@/assets/js/settings'
export default {
  data() {
    return {
      id: '',
      content: '',
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式0
        preview: true // 预览
      },
      img_file: {},
      contributeForm: {
        title: '',
        class: '',
        content: '',
        titleImg: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          {
            min: 10,
            max: 75,
            message: '长度在 10 到 75 个字符',
            trigger: 'blur'
          }
        ],
        class: [{ required: true, message: '请选择分类', trigger: 'change' }],
        content: [{ required: true, message: '请填写内容', trigger: 'blur' }],
        titleImg: [
          { required: true, message: '请上传标题图片', trigger: 'blur' }
        ]
      },
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  computed: {
    classOptions() {
      return this.$store.state.classification.allClass.map((item) => {
        return {
          value: item.id,
          label: item.name,
          children: item.map.map((itemMap) => {
            return {
              value: itemMap.id,
              label: itemMap.name
            }
          })
        }
      })
    },
    appUrl() {
      return APP__URL
    }
  },
  async created() {
    const id = this.$route.params.id
    if (id) {
      this.id = id
      const { status, data } = await this.$axios.get('/news/re', {
        params: { id }
      })
      if (status === 200 && data.code === 1) {
        const item = data.data
        this.contributeForm.title = item.title
        this.contributeForm.class = item.class
        this.content = item.content
        this.contributeForm.titleImg = item.titleImg
      }
    }
  },
  methods: {
    submitForm(formName) {
      const self = this
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (self.id) {
          } else {
            if (!_.isEmpty(self.img_file)) {
              const formdata = new FormData()
              for (const _img in self.img_file) {
                formdata.append(_img, self.img_file[_img])
              }
              const {
                status: statusImg,
                data: dataImg
              } = await self.$axios.post('/news/img', formdata, {
                headers: { 'Content-Type': 'multipart/form-data' }
              })
              if (statusImg === 200 && dataImg.code === 1) {
                const fileImg = dataImg.fileImg
                self.contributeForm.titleImg = fileImg[0][1]
                _.forIn(fileImg, function(value) {
                  self.$refs.md.$img2Url(value[0], IMAGES + '/' + value[1])
                })
              } else if (statusImg === 413) {
                self.$message({
                  message: '图片过大，请上传2M以内的图片',
                  type: 'error'
                })
                return
              } else {
                self.$message({
                  message: dataImg.msg,
                  type: 'error'
                })
                return
              }
            }
            const { status, data } = await self.$axios.post('/news', {
              title: self.contributeForm.title,
              classId: self.contributeForm.class[1],
              content: self.contributeForm.content,
              titleImg: self.contributeForm.titleImg
            })
            if (status === 200) {
              if (data.code === 0) {
                self.$message({
                  message: '投稿成功',
                  type: 'success'
                })
              } else {
                self.$message({
                  message: data.msg,
                  type: 'error'
                })
              }
            }
          }
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    $imgAdd(pos, $file) {
      // 缓存图片信息
      this.img_file[pos] = $file
    },
    $imgDel(pos) {
      delete this.img_file[pos]
    },
    change(value, render) {
      this.contributeForm.content = value
    },
    handleRemove(file, fileList) {},
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccess(response, file, fileList) {
      if (response.code === 1) {
        this.contributeForm.titleImg = response.fileImg[0][1]
      }
    },
    handleBeforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleOnExceed(files, fileList) {
      this.$message.error(`上传${files[0].name}失败，只能上传一张标题图片`)
    }
  }
}
</script>

<style lang="scss" scoped>
.contribute {
  margin-top: 60px;
}
.mavonEditor {
  width: 100%;
  height: 100%;
}
.markdown-body {
  height: 400px;
}
</style>
